#include "mainwindow.h"
#include <QHeaderView>
#include <iostream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      control_(new Control(this)),
      dataView_(new DataView(this)) {

    qRegisterMetaType<mavlink_message_t>("mavlink_message_t");
    QVBoxLayout *rightLayout = new QVBoxLayout;
    rightLayout->addWidget(dataView_);
    rightLayout->addWidget(control_);
        // 设置比例为 7:3
    rightLayout->setStretch(0, 8);  // button1 占7
    rightLayout->addStretch();

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(rightLayout);
    setCentralWidget(centralWidget);

    createConnect();
    std::cout<<"MainWindow created"<<std::endl;

}

void MainWindow::createConnect() {
    // connect(this, &MainWindow::mavlinkMessageReceived, dataView_, &dataView_::handleMavlinkMessage);
    connect(control_, &Control::connectClicked, this, &MainWindow::serverLinkClicked);
    connect(control_, &Control::cmdBtnClicked, this, &MainWindow::cmdBtnClicked);
    connect(this, &MainWindow::mavlinkMessageReceived, dataView_, &DataView::receiveMsgSlot);
}

void MainWindow::serverLinkClicked(const std::string ip, int port) {
    mavlinkServer.start(ip, port);
    mavlinkServer.set_mavlink_message_callback(std::bind(&MainWindow::handleMavlinkMessage, this, std::placeholders::_1));
}

void MainWindow::cmdBtnClicked(const int cmd_type , const int drone_id, const std::vector<float> data_f, 
                        const std::vector<int> data_i, std::string data_s) {
    mavlink_message_t message;
    mavlink_mission_cmd_t mission_cmd;
    mission_cmd.seq = seq_++;
    mission_cmd.drone_type = 1;
    mission_cmd.drone_id = drone_id;
    mission_cmd.cmd = cmd_type;

    for(int i=0; i<8 && i <data_f.size();i++)
        mission_cmd.param_float[i] = data_f[i];
    for(int i=0; i<8 && i <data_i.size();i++)
        mission_cmd.param_int[i] = data_i[i];
    
    std::size_t length = data_s.copy(mission_cmd.param_str, sizeof(mission_cmd.param_str) - 1);
    mission_cmd.param_str[length] = '\0';
     
    mavlink_msg_mission_cmd_encode(1, 200, &message, &mission_cmd);
    mavlinkServer.send_mavlink_message(message);
}

void MainWindow::handleMavlinkMessage(const mavlink_message_t& message) {
    std::cout<<"MainWindow::handleMavlinkMessage"<<std::endl;
    emit mavlinkMessageReceived(message);
}
